<template>
  <div class="box">
    <div class="card-container">
      <el-row :gutter="10">
        <el-form :model="queryParams" label-width="100px" ref="queryForm" :inline="true" v-show="showSearch">
          <el-col :span="19" :offset="0">
            <el-form-item label="设备序列号" prop="code">
              <el-input v-model="queryParams.code" :style="'width:215px'" placeholder="请输入设备序列号" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="queryParams.deviceType" clearable :style="'width:215px'" placeholder="请选择设备类型">
                <el-option v-for="item in this.dict.type.sys_device_mode" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="设备型号" prop="modelId">
              <el-select v-model="queryParams.modelId" clearable :style="'width:215px'" placeholder="请选择设备型号">
                <el-option v-for="item in modList" :key="item.modelId" :label="item.model" :value="item.modelId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="软件版本" prop="version">
              <el-input v-model="queryParams.version" :style="'width:215px'" placeholder="请输入软件版本" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="queryParams.projectId" clearable :style="'width:215px'" placeholder="请选择所属项目">
                <el-option v-for="item in projectList" :key="item.projectId" :label="item.shortName"
                  :value="item.projectId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="onlineStatus">
              <el-select v-model="queryParams.onlineStatus" :style="'width:215px'" placeholder="请选择状态" clearable
                size="small">
                <el-option v-for="dict in dict.type.sys_on_line_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item>
              <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <div class="card-container">
      <div class="body-title">
        <div class="body-title-left">设备总览</div>
        <div class="body-title-right">
          <el-button size="mini" :disabled="isonline" v-hasPermi="['device:restart']" @click="handelRestart"
            v-show="!multiple">重启</el-button>
          <el-button size="mini" v-show="!multiple" v-hasPermi="['device:disconnectDevice']" @click="handleConnect"
            :disabled="isonline">断开</el-button>
          <el-button icon="el-icon-delete" size="mini" :disabled="multiple" v-hasPermi="['device:remove']"
            v-show="!multiple" @click="handleDelete">删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading" height="440" :row-key="getRowKeys" ref="table" :data="deviceList"
        @selection-change="handleSelectionChange">
        <!-- :selectable="checkSelectable" -->
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="设备序列号" min-width="120" align="center" prop="code" />
        <el-table-column label="软件版本" min-width="80" align="center" prop="softwareVersion" />
        <el-table-column label="固件版本" min-width="100" align="center" prop="firmwareVersion" show-overflow-tooltip />
        <el-table-column label="设备类型" min-width="100" align="center" prop="deviceType">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceType == '1' ? '预警终端' : '预警喇叭' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备型号" min-width="100" align="center" prop="model" />
        <!-- <el-table-column label="设备厂商" min-width="100" align="center" prop="fac" /> -->
        <el-table-column label="所属项目" min-width="120" align="center" prop="projectName" />
        <el-table-column label="管理状态" min-width="80" align="center" prop="onlineStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_on_line_status" :value="scope.row.onlineStatus" />
          </template>
        </el-table-column>
        <el-table-column label="上报时间" min-width="160" align="center" prop="reportTime" />
        <el-table-column label="状态时长" min-width="160" align="center" prop="statusDuration">
          <template slot-scope="scope">
            <span>{{ timeDate(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" min-width="200" align="center" prop="address" show-overflow-tooltip>
        </el-table-column>
        <el-table-column width="220" :colspan="2" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleRouter(scope.row)" v-hasPermi="['device:remotely']"
              :disabled="scope.row.onlineStatus == '0'">操作</el-button>
            <el-button size="mini" type="text" @click="handleDeviceInfo(scope.row)" v-hasPermi="['device:deviceDetail']"
              :disabled="scope.row.onlineStatus == '0'">详情</el-button>
            <el-button size="mini" type="text" @click="handlePush(scope.row)" v-hasPermi="['device:drill']"
              :disabled="scope.row.onlineStatus == '0'">演练</el-button>
            <el-button size="mini" type="text" @click="handleLog(scope.row)" v-hasPermi="['device:log']">日志</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <el-dialog :title="''" :close-on-click-modal="false" v-if="openDrawer" width="80%" :visible.sync="openDrawer">
      <ReplyRecord :parentId="deviceId" :pageData="pageData" v-if="openDrawer" />
    </el-dialog>
    <el-dialog :close-on-click-modal="false" v-if="openDeviceIfo" width="60%" :visible.sync="openDeviceIfo">
      <device-info :pageData="pageData" v-if="openDeviceIfo" />
    </el-dialog>
    <el-dialog :close-on-click-modal="false" v-if="pushVisible" width="80%" :visible.sync="pushVisible">
      <push-page :pageData="pageData" v-if="pushVisible" />
    </el-dialog>
    <!-- 软件更新 -->
    <el-dialog :close-on-click-modal="false" v-if="logOpen" width="80%" :visible.sync="logOpen">
      <log-view :pageData="pageData"></log-view>
    </el-dialog>
    <!-- 设备重启 -->
    <el-dialog :title="'系统提示'" :close-on-click-modal="false" :custom-class="'sysDialog'" width="400px" v-if="sysOpen"
      :visible.sync="sysOpen">
      <div class="card-container">
        <div class="sysBox">
          <span>成功: <i>{{ sysfail.successNum }}</i></span>
          <span style="margin-left: 30px">失败: <i>{{ sysfail.failNum }}</i></span>
          <ul class="sysList">
            <li v-for="item in sysfail.failDevices" :key="item">
              <div>{{ item }}</div>
              <div>失败</div>
            </li>
          </ul>
        </div>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import {
  listAllDevice,
  deviceDelete,
  deviceRestart,
  disconnectDevice,
} from "@/api/allDevice/allDevice";
import { getDevice } from "@/api/device/device";
import ReplyRecord from "@/views/components/reply"
import deviceInfo from "@/views/components/deviceInfo"
import pushPage from "@/views/components/pushPage"
import { getProject } from "@/api/runningLog/runningLog.js";
import logView from "@/views/components/logView";
// import { getProject } from '@/api/common.js';
let validate1 = (rule, value, callback) => {
  if (value > 180) {
    callback(new Error("最大值为180"));
  } else {
    callback();
  }
};
let validate2 = (rule, value, callback) => {
  if (value > 90) {
    callback(new Error("最大值为90"));
  } else {
    callback();
  }
};
export default {
  name: "Device",
  dicts: [
    "sys_normal_disable",
    "sys_device_mode",
    "sys_on_line_status",
    "sys_normal_abnormal",
    "sys_mqtt_status",
    "sys_ntp_status",
    "sys_log_type"
  ],
  data() {
    return {
      logOpen: false,//日志弹窗
      pageData: {},
      openDrawer: false,//远程控制弹窗
      openDeviceIfo: false,//状态详情弹窗
      sysfail: { failNum: 0, successNum: 0, failDevices: [] },//设备重启状态
      sysOpen: false,//设备重启弹窗
      projectList: [],
      modList: [],
      selection: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      isonline: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        version: null,
        type: null,
        deviceType: null,
        modelId: null,
        projectId: null,
        onlineStatus: null,
      },
      timer: null,
      pageData: {},
      pushVisible: false,
      codes: [],
      deviceId: ''//设备id
    };
  },

  created() {
    // let blob = new Blob([res]);   // 返回的文件流数据
    // console.log('blob: ', blob);
    // let url = window.URL.createObjectURL(blob);  // 将他转化为路径
    // this.mapSrc = url  // 将转换出来的路径赋值给变量，其实和上一步结合就可以
    // 路由跳转获取参数
    if (this.$route.query.onlineStatus) {
      this.queryParams.onlineStatus = this.$route.query.onlineStatus
    }
    // 创建定时器实时刷新列表
    this.getList();
    this.timer = setInterval(() => {
      this.getList();
    }, 5000)
  },
  activated() {
    this.getList();
  },
  // beforeRouteEnter(to, from, next) {
  //   next((vm) => {
  //     addEventListener('resize', () => {
  //       vm.$nextTick(() => {
  //         vm.$refs.tabel.doLayout();
  //       });
  //     });
  //   });
  // },
  mounted() {
    this.getConfig();
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  components: {
    ReplyRecord,
    deviceInfo,
    pushPage,
    logView
  },
  methods: {
    // 日志弹窗
    handleLog(item) {
      this.pageData = item
      this.logOpen = true
    },

    // 远程操作按钮事件
    async handleRouter(row) {
      this.deviceId = row.deviceId
      this.pageData = row
      this.openDrawer = true
    },

    /**状态详情操作 */
    handleDeviceInfo(row) {
      this.pageData = row
      this.openDeviceIfo = true
    },

    getRowKeys(row) {
      return row.deviceId;
    },
    // 时间毫秒格式化
    timeDate(row) {
      const time = new Date() - new Date(row.statusDuration);
      let day = Math.floor(time / 1000 / 60 / 60 / 24);
      let h = Math.floor(time / 1000 / 60 / 60) % 24;
      let m = Math.floor((time / 1000 / 60) % 60);
      let s = Math.floor((time / 1000) % 60);
      return `${day > 0 ? day + "天" : ""}${h > 0 ? h + "小时" : ""}${m > 0 ? m + "分钟" : ""
        }${s > 0 ? s + "秒" : ""}`;
    },
    // 推送弹窗
    handlePush(row) {
      this.pageData = row
      this.pushVisible = true
    },
    // 设备重启
    async handelRestart() {
      const res = await deviceRestart({ deviceCodes: this.codes, type: 1 });
      if (res.code == 200) {
        // this.$modal.alertError(res.data);
        this.sysfail = res.data;
        this.sysOpen = true;
        this.getList();
      }
      // console.log(res);
    },
    // 断开设备操作按钮
    async handleConnect() {
      const res = await disconnectDevice(this.codes.join(','));
      if (res.code == 200) {
        setTimeout(() => {
          this.getList();
        }, 1000)
      }
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listAllDevice(this.queryParams).then(async (response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.ids = this.selection.map((item) => item.deviceId);
      this.codes = this.selection.map((item) => item.code);
      this.isonline = this.selection.some(item => {
        return item.onlineStatus == '0'
      })
      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;
    },
    // 查询项目列表设备列表
    async getConfig() {
      this.modList = await this.$api.getMod();
      const res = await getProject();
      if (res.code == 200) {
        this.projectList = res.data;
      }
    },

    /** 删除按钮操作 */
    handleDelete() {
      const deviceIds = this.ids;
      this.$modal
        .confirm("是否确认删除设备？")
        .then(function () {
          return deviceDelete(deviceIds);
        })
        .then(() => {
          this.$refs.table.clearSelection();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.isYN {
  display: flex;

  label {
    margin-left: 20px;
  }
}



.body-title {
  display: flex;
  position: relative;
  // justify-content: space-between;
  align-items: center;
}

.body-title-left {
  height: 100%;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #fff;
  line-height: 64px;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #000;
}

// ::v-deep .el-button--text{
//   color: #6AD7CA;
// }
// ::v-deep .el-button.is-disabled.el-button--text{
//   color: #fff;
// }


.body-title-right {
  position: absolute;
  right: 0;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
  // appearance: textfield !important;
}

::v-deep .el-dialog[aria-label="演练"],
::v-deep .el-dialog[aria-label="详情"] {
  .el-dialog__header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .24);
    filter: blur(2px);
    z-index: 1;
  }

  .el-dialog__title {
    margin-left: 20px
  }

  .el-dialog__headerbtn {
    z-index: 2;
  }
}

::v-deep .sysDialog:not(.is-fullscreen) {
  margin-top: 24vh !important;
}

::v-deep .el-drawer__body {
  overflow-y: scroll;
}

::v-deep .el-drawer__header {
  font-weight: 600;
  font-size: 18px;
  color: #000;
}

.mb8 {
  height: 30px;
}

.sysBox {
  padding: 0 20px;

  >span {
    >i {
      font-style: normal;
      color: #409eff;
    }
  }

  .sysList {
    margin: 0;
    padding: 0;
    margin-top: 10px;
    height: 200px;
    overflow-y: auto;

    >li {
      list-style: none;
      padding: 0px 20px;
      height: 40px;
      line-height: 40px;
      background: rgba(144, 147, 153, 0.2);
      display: flex;

      div {
        flex: 1;

        &:nth-child(2) {
          color: red;
        }
      }
    }

    >li:nth-child(2n) {
      background: rgba(144, 147, 153, 0.5);
    }
  }
}

::v-deep .el-dialog__title {
  margin-left: 180px;
  color: #fff;


}

// ::v-deep .el-dialog__header::before{
//     content: '';
//     position: absolute;
//     top: 0;
//     left: 0;
//     width: 100%;
//     height: 100%;
//     background-color: rgba(0, 0, 0,.24);
//     filter: blur(2px);
//     z-index: 1;
//   }
//   ::v-deep  .el-dialog__headerbtn{
//     z-index: 2;
//   }
// ::v-deep .el-dialog__body{
// padding: 0;
// }
</style>
